﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ITunesSolver.Helpers;
using ITunesSolver.Helpers.Validation;

namespace ITunesSolver.UI
{


    /// <summary>
    /// Interaction logic for LoadFile.xaml
    /// </summary>
    public partial class SelectFile : UserControl
    {
        public delegate void FileSelectedDelegate(object sender, string fileName);
        public event FileSelectedDelegate FileSelectedEvent;

        public string FileName { get; set; }

        public SelectFile()
        {
            InitializeComponent();

            BindingExpression expression = txtFileName.GetBindingExpression(TextBox.TextProperty);

            //clear validation because it is not automatically cleared
            if (expression != null)
            {
                expression.UpdateSource();
                Validation.ClearInvalid(expression);
            }

        }

        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            string fileName = string.Empty;
            fileName = FileHelper.SelectFile("iTunes Music Library.xml");

            txtFileName.Text = fileName;
            FileName = fileName;

            Validate();

            UpdateLayout();

            if (FileSelectedEvent != null) FileSelectedEvent(sender, fileName);
        }

        public bool Validate()
        {
            BindingExpression expression = txtFileName.GetBindingExpression(TextBox.TextProperty);
            if (expression != null)
            {
                expression.UpdateSource();
                Validation.ClearInvalid(expression);
            }

            if (FileName == null || FileName == string.Empty)
            {
                StringRangeValidationRule rule = new StringRangeValidationRule();
                rule.ErrorMessage = "Filename is required";

                ValidationError error = new ValidationError(rule, expression, "Filename is required.", null);
                
                Validation.MarkInvalid(expression, error);

                UpdateLayout();

                return false;
            }

            UpdateLayout();

            Validation.ClearInvalid(expression);
            return true;
        }
    }
}
